<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Plivo\Exceptions\PlivoResponseException;
use Plivo\Exceptions\PlivoRestException;
use GuzzleHttp\Client;

class PlivoService
{

    /**
     *  创建端点
     * @param $appId
     */
    public function createEndpoint($appId){
        try {
            $res = [];
            $username = 'a'.substr(md5(time()), 0, 6);
            $password = substr(md5(time()), 0, 6);
            $response = app('Plivo')->endpoints->create(
                $username,
                $password,
                $username,
                $appId
            );
            if($response->message == 'created'){
                $res['username'] = $response->username;
                $res['password'] = $password;
                $res['endpoint_id'] = $response->endpointId;
                return $res;
            }
        }
        catch (PlivoResponseException $ex) {
            Log::error('端点创建失败',[$ex]);
        }
        return false;
    }

    /**
     * 删除端点
     * @param $endpointId
     */
    public function deleteEndpoint($endpointId){
        try {
            $response = app('Plivo')->endpoints->delete(
                $endpointId
            );
            return true;
        }
        catch (PlivoResponseException $ex) {
            Log::error('端点删除失败',[$ex]);
        }
        return false;
    }

    /**
     * 电话号码搜索
     */
    public function searchPhone(){
        try {
            $response = app('Plivo')->phonenumbers->list(
                'HK',
                [
                'limit' => 1,
        	 ]
            );
            if(isset($response->resources[0]->properties)){
                return $response->resources[0]->properties;
            }
        }
        catch (PlivoRestException $ex) {
            Log::error('电话搜索失败',[$ex]);
        }
        return false;
    }

    /**
     * 电话号码购买
     * @$number 手机号
     * @return $res->number
     */
    public function buy($number){
        try {
            $response = app('Plivo')->phonenumbers->buy(
                $number
            );
            if($response->message == 'created'){
                return true;
            }
        }
        catch (PlivoRestException $ex) {
            Log::error('电话购买失败',[$ex]);
        }
        return false;
    }

    /**
     * 电话号码绑定App
     * @param $number
     * @param $appId
     */
    public function numberUpdate($number, $appId){
        try {
            $response = app('Plivo')->numbers->update(
                $number,
                ['app_id' => $appId, 'alias' => 'used']
            );
            if($response->message == 'changed'){
                return true;
            }
        }
        catch (PlivoRestException $ex) {
            Log::error('电话绑定应用失败',[$ex]);
        }
        return false;
    }

    /**
     * 电话列表
     */
    public function phoneList(){
        try {
            $response = app('Plivo')->numbers->list(
                [
                    'limit' => 1000,
                ]
            );
            if($response){
                $list = [];
                foreach ($response->resources as $v){
                    $list[] = $v->number;
                }
            }
            return $list;
        }
        catch (PlivoRestException $ex) {
            Log::error('电话列表',[$ex]);
        }
    }


    /**
     * 创建应用
     */
    public function createApp(){
        try {
            $response = app('Plivo')->applications->create(
                'App-'.date('dHis'),
                [
                    'answer_url' => env('APP_URL').'/api/plivo/xml',
                    'answer_method' => 'POST',
                    'hangup_url' => env('APP_URL').'/api/plivo/hangup',
                    'hangup_method' => 'POST'
                ]
            );
            if($response->message == 'created'){
                return $response;
            }
        }
        catch (PlivoRestException $ex) {
            Log::error('Plivo创建应用失败',[$ex]);
        }
        return false;
    }

    /**
     * 更新应用
     * @param $appID
     * @param $to 打给谁
     * @param $id 会员id
     * @param $user_id 后台用户Id
     * @param $task_id 任务id
     * @param $from_id
     * @param  $phoneSettingId
     */
    public function editApp($appId,$to,$id,$user_id,$task_id='',$from,$phoneSettingId){
        try {
            $response = app('Plivo')->applications->update(
                $appId,
                [
                    'answer_url' => env('APP_URL').'/api/plivo/xml'."?to={$to}&id={$id}&user_id={$user_id}&from={$from}&phone_setting_id={$phoneSettingId}&task_id={$task_id}"
                ]
            );
           if($response->message == 'changed'){
                return $response;
           }
        }
        catch (PlivoRestException $ex) {
            Log::error('Plivo应修改URL失败',[$ex]);
        }
        return false;
    }

    /**
     *  重置应用的answer_url
     */
    public function resetApp($appId){
        try {
            $response = app('Plivo')->applications->update(
                $appId,
                [
                    'answer_url' => env('APP_URL').'/api'
                ]
            );
            if($response->message == 'changed'){
                return $response;
            }
        }
        catch (PlivoRestException $ex) {
            Log::error('Plivo应重置URL失败',[$ex]);
        }
        return false;
    }

    /**
     * 删除应用
     * @param $appID
     */
    public function deleteApp($appId){
        try {
            $response = app('Plivo')->applications->delete(
                $appId
            );
            if($response->message == '204'){
                return true;
            }
        }
        catch (PlivoRestException $ex) {
            Log::error('Plivo创建应删除失败',[$ex]);
        }
        return false;
    }

    /**
     * 电话绑定应用id
     * @param $phone
     * @param $appId
     */
    public function phoneBindApp($phone, $appId){
        try {
            $response = app('Plivo')->numbers->update(
                $phone,
                ['app_id' => $appId]
            );
           if($response->message == 'changed'){
                return $response;
           }
        }
        catch (PlivoRestException $ex) {
            Log::error('Plivo应用绑定电话失败',[$ex]);
        }
    }

    /**
     * @return string
     * @parma $path
     */
    public function voiceUpload($path,$file_name){
        $guzzle = new Client();
        try{
            $res = $guzzle->request('GET', $path);
            if($res->getStatusCode() == 200){
                return voiceUpload($path,$file_name);
            }
        }catch (\Exception $e){
            Log::error('Plivo下载录音到本地',[$e]);
        }
        return false;
    }
}